import axios from "../../http/axios.js";
import {
  apiUpdateNameIdcard,
  apiGetUserInfo
} from "../../http/server.js";
import {
  regExpName,
  regExpIdCard
} from "../../utils/regular.js";
Page({
  data: {
    titleOne: {
      key: "身份证实名",
      value: "该信息仅用于证明您的真实身份，保障您的合法权益，请放心填写"
    },
    titleTwo: {
      key: "姓名",
      value: ""
    },
    titleThree: {
      key: "身份证号",
      value: ""
    }
  },

  onLoad: function(options) {
    this.setUserInfo();
  },

  onReady: function() {

  },

  onShow: function() {

  },
  setUserInfo: function() {
    var userInfo = wx.getStorageSync("userInfo");
    var titleTwo = this.data.titleTwo;
    titleTwo.value = userInfo.userName || "";
    this.setData({
      titleTwo: titleTwo
    })
    var titleThree = this.data.titleThree;
    titleThree.value = userInfo.idCard || "";
    this.setData({
      titleThree: titleThree
    })
  },
  //修改姓名
  updateInputValue: function(e) {
    var item = e.currentTarget.dataset.item;
    if (item.key == "姓名") {
      var titleTwo = this.data.titleTwo;
      titleTwo.value = e.detail.value;
      this.setData({
        titleTwo: titleTwo
      })
    } else {
      var titleThree = this.data.titleThree;
      titleThree.value = e.detail.value;
      this.setData({
        titleThree: titleThree
      })
    }
  },
  //进行手机号验证
  testPhone: function() {
    var name = this.data.titleTwo.value;
    var idCard = this.data.titleThree.value;
    if (!name.length) {
      wx.showToast({
        title: "请输入姓名",
        icon: "none"
      });
      return false;
    }
    if (!regExpName.test(name)) {
      wx.showToast({
        title: "请输入正确的姓名",
        icon: "none"
      });
      return false;
    }
    if (!idCard.length) {
      wx.showToast({
        title: "请输入身份证号",
        icon: "none"
      });
      return false;
    }
    if (!regExpIdCard.test(idCard)) {
      wx.showToast({
        title: "请输入正确的身份证号",
        icon: "none"
      });
      return false;
    }
    return true;
  },
  //点击完成
  handleClickSuccess: function() {
    var test = this.testPhone();
    if (!test) {
      return;
    }
    var userInfo = wx.getStorageSync("userInfo");
    var data = {
      userId: userInfo.userId,
      userName: this.data.titleTwo.value,
      idCard: this.data.titleThree.value
    }
    axios({
        url: apiUpdateNameIdcard,
        method: "POST",
        data: data
      })
      .then(res => {
        axios({
          url: apiGetUserInfo,
          data: {
            userId: userInfo.userId
          }
        }).then(res => {
          wx.setStorageSync("userInfo", res);
          wx.showToast({
            title: "实名认证完成",
            icon: "none"
          });
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        })
      })
  },
  onHide: function() {},

  onUnload: function() {},
})